package com.example.xd.myijkplayer.textureview

import android.content.Context
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.example.xd.myijkplayer.ExitTinyWindow
import com.example.xd.myijkplayer.R
import com.example.xd.myijkplayer.utils.TimeFormatUtil
import com.example.xd.myijkplayer.view.FloatWindowManager
import com.example.xd.permissionlibrary.utils.toast
import kotlinx.android.synthetic.main.activity_texture_view.*
import kotlinx.android.synthetic.main.stard_texture_layout.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.MainThreadSupport
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import tv.danmaku.ijk.media.player.IMediaPlayer
import tv.danmaku.ijk.media.player.IjkTimedText

/**
 * @auther XuDan on 2020/9/15.
 */
class StardTextureView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), ITexture, View.OnClickListener,
    StardTextureListener {
    init {
        EventBus.getDefault().register(this)
        initView(context, attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?) {
        LayoutInflater.from(context).inflate(R.layout.stard_texture_layout, this, true)
        stard_texture.setStadrTextureListener(this)
        stard_img_start.setOnClickListener(this)
        stard_bottom_img_pause.setOnClickListener(this)
        stard_img_scal.setOnClickListener(this)
        stard_img_small.setOnClickListener(this)
    }

    var full_w = 0
    var full_h = 0
    var stard_w = 0
    var stard_h = 0
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        full_h = MeasureSpec.getSize(heightMeasureSpec)
        full_w = MeasureSpec.getSize(widthMeasureSpec)
        stard_w = MeasureSpec.getSize(widthMeasureSpec)
        stard_h = stard_w * 6 / 9
        val stard_lp = stard_texture.layoutParams
        stard_lp.height = stard_h
        stard_lp.width = stard_w
        stard_texture.layoutParams = stard_lp
        val fl_lp = stard_fl.layoutParams
        fl_lp.width = stard_w
        fl_lp.height = stard_h
        stard_fl.layoutParams = fl_lp
        setMeasuredDimension(stard_w, stard_h)
    }

    override fun onClick(v: View?) {
        when (v) {
            stard_img_start -> {
                start()
            }
            stard_bottom_img_pause -> {
                if (stard_texture.isPlaying()) {
                    pause()
                } else {
                    restart()
                }
            }
            stard_img_scal -> {
                if (isFullScreen()) {
                    exitFullScreen()
                } else {
                    enterFullScreen()
                }
            }
            stard_img_small -> {
                if (!isTinyWindow()) {
                    val bitmap = stard_texture.getBitmap()
                    stard_fl_img.setImageBitmap(bitmap)
                    stard_fl_img.visibility = View.VISIBLE
                    stard_fl.visibility = View.GONE
                    enterTinyWindow()
                }
            }
        }
    }

    private var timeHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                1 -> {
                    if (!isPaused()) {
                        stard_tv_time.setText(
                            TimeFormatUtil.stringForTime(currentPosition()) + "/" + TimeFormatUtil.stringForTime(
                                duration()
                            )
                        )
                        stard_bottom_sb.setProgress((currentPosition() * 100 / duration()).toInt())
                        val obtain = Message.obtain()
                        obtain.what = 1
                        sendMessageDelayed(obtain, 1000)
                    }


                }
            }
        }
    }

    override fun start() {
        stard_texture.start()
        stard_img_start.visibility = View.GONE
        stard_bottom_img_pause.setImageResource(R.drawable.ag_btn_movie_stop_bottom)
        val msg = Message.obtain()
        msg.what = 1
        timeHandler.sendMessage(msg)
    }

    override fun restart() {
        stard_texture.restart()
        stard_img_start.visibility = View.GONE
        stard_bottom_img_pause.setImageResource(R.drawable.ag_btn_movie_stop_bottom)
        val msg = Message.obtain()
        msg.what = 1
        timeHandler.sendMessage(msg)
    }

    override fun pause() {
        stard_texture.pause()
        stard_img_start.visibility = View.VISIBLE
        stard_bottom_img_pause.setImageResource(R.drawable.ag_btn_movie_play_bottom)
    }

    override fun seekTo(pos: Long) {
        stard_texture.seekTo(pos)
    }

    override fun release() {
        stard_texture.release()
        EventBus.getDefault().unregister(this)
    }

    override fun setPath(path: String) {
        stard_texture.setPath(path)
    }

    override fun isBufferingPlaying(): Boolean {
        TODO("Not yet implemented")
    }

    override fun isBufferingPaused(): Boolean {
        TODO("Not yet implemented")
    }

    override fun isPlaying(): Boolean {
        return stard_texture.isPlaying()
    }

    override fun isPaused(): Boolean {
        return stard_texture.isPaused()
    }

    override fun duration(): Long {
        return stard_texture.duration()
    }

    override fun currentPosition(): Long {
        return stard_texture.currentPosition()
    }

    override fun bufferPercentage(): Int {
        TODO("Not yet implemented")
    }

    override fun isFullScreen(): Boolean {
        return stard_texture.isFullScreen()
    }

    override fun enterFullScreen() {
        this.rotation = 90f
        this.scaleX = 1f
        this.scaleY = 1f
        stard_texture.enterFullScreen()
        stard_img_scal.setImageResource(R.drawable.jz_shrink)

    }

    override fun exitFullScreen() {
        this.rotation = 0f
        this.scaleX = 1f
        this.scaleY = 1f
        stard_texture.exitFullScreen()
        stard_img_scal.setImageResource(R.drawable.jz_enlarge)
    }

    override fun isTinyWindow(): Boolean {
        return stard_texture.isTinyWindow()
    }

    override fun enterTinyWindow() {
        stard_texture.enterTinyWindow()
        FloatWindowManager.getInstance().applyOrShowFloatWindow(context, stard_texture)
    }

    override fun exitTinyWindow() {
        FloatWindowManager.getInstance().dismissWindow()
        stard_fl_img.visibility = View.GONE
        stard_fl.visibility = View.VISIBLE
        val parent: FrameLayout = stard_texture.parent as FrameLayout
        if (parent != null) {
            parent.removeView(stard_texture)
        }
        stard_fl_tvc.addView(stard_texture)
        stard_texture.exitTinyWindow()

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun exit(msg: ExitTinyWindow) {
        exitTinyWindow()
    }

    override fun onSeekComplete(p0: IMediaPlayer?) {
    }

    override fun onTimedText(p0: IMediaPlayer?, p1: IjkTimedText?) {
    }

    override fun onVideoSizeChanged(p0: IMediaPlayer?, p1: Int, p2: Int, p3: Int, p4: Int) {
    }

    override fun onInfo(p0: IMediaPlayer?, p1: Int, p2: Int): Boolean {
        return true
    }

    override fun onError(p0: IMediaPlayer?, p1: Int, p2: Int): Boolean {
        return true
    }

    override fun onCompletion(p0: IMediaPlayer?) {
        seekTo(0)
        pause()
    }

    override fun onBufferingUpdate(p0: IMediaPlayer?, p1: Int) {
    }

    override fun onPrepared(mediaPlayer: IMediaPlayer?) {
    }

}